package com.zaink.jettytesting;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.util.thread.ThreadPool;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author zenghy
 **/
@Slf4j
@Configuration
public class JettyConfiguration {

    private final ApplicationArguments arguments;

    public JettyConfiguration(ApplicationArguments arguments) {
        this.arguments = arguments;
    }

    @Bean
    public ThreadPool threadPool() {
        QueuedThreadPool threadPool = new QueuedThreadPool();
        // 最大线程数，默认为200
        List<String> maxThreads = arguments.getOptionValues("server.jetty.max-threads");
        if (!CollectionUtils.isEmpty(maxThreads)) {
            threadPool.setMaxThreads(Integer.parseInt(maxThreads.get(0)));
        }
        return threadPool;
    }

    @Bean
    public JettyServletWebServerFactory jettyServletWebServerFactory(ThreadPool threadPool) {
        JettyServletWebServerFactory factory = new JettyServletWebServerFactory();
        factory.setThreadPool(threadPool);
        return factory;
    }
}
